"use strict";
const Controller = require("egg").Controller;
// 文件存储
const fs = require("fs");
const path = require("path");
const pump = require("pump");

class UploadController extends Controller {
  async upload() {
    let parts = this.ctx.multipart({ autoFields: true });
    console.log(parts);
    let stream,
      img_list = "";
    while ((stream = await parts()) != null) {
      if (!stream.filename) {
        break;
      }
      // 文件名为：时间戳+随机字符串+.文件后缀
      let filename =
        new Date().getTime() +
        Math.random().toString(36).substr(2) +
        path.extname(stream.filename).toLocaleLowerCase();

      // 上传图片的目录
      let target = "app/public/admin/upload/" + filename;

      img_list = "/public/admin/upload/" + filename;

      let writeStream = fs.createWriteStream(target);

      await pump(stream, writeStream);
    }
    console.log(parts.field); // 表单其他数据，可以根据需要处理

    this.ctx.body = {
      code: 200,
      msg: {
        url: img_list,
        fields: parts.field
      }
    };
  }
}

module.exports = UploadController;
